package com.example.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class DownloadController {
	
	@Value("${baseDir}")
	String baseDir;
	
	@Autowired
	MediumCrawler mediumCrawler;
	
	AtomicBoolean busing=new AtomicBoolean();
	
	
	@GetMapping("/download")
	public ResponseEntity<Resource> download() throws IOException {
		if(!busing.compareAndSet(false, true)){
			throw new ResponseStatusException(HttpStatus.FORBIDDEN,"正在处理上一个提交,请勿频繁点击!");	
		}
		
		try {
			String pdfDir = baseDir+"\\result\\pdf";
			String htmlDir = baseDir+"\\result\\html";
			String zipFile = baseDir+"\\result.zip";
			
			FileUtil.del(zipFile);
			
			FileUtil.del(pdfDir);
			FileUtil.del(htmlDir);
			FileUtil.mkdir(pdfDir);
			FileUtil.mkdir(htmlDir);
			
			
			mediumCrawler.download();	
			
			log.info("--------------download--------------");
	
			ZipUtils.pack(pdfDir, zipFile);
	
			File file = new File(zipFile);
			InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
	
			return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=" + file.getName())
					.contentLength(file.length()).body(resource);
		}finally {
			busing.set(false);
		}
//		return  ResponseEntity.ok().body(null);
	}
}
